package cn.wyl.pet.service.impl;

import cn.wyl.org.domain.Department;
import cn.wyl.pet.domain.PetType;
import cn.wyl.pet.mapper.PetTypeMapper;
import cn.wyl.pet.service.IPetTypeService;
import cn.wyl.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> petTypeTree() {
        List<PetType> petTypes = petTypeMapper.findAll();
        //将所有宠物类型查询出来 - 装到map集合 => 为了方便通过id找宠物类型对象
        HashMap<Long, PetType> map = new HashMap<>();
        for (PetType type : petTypes) {
            map.put(type.getId(), type);
        }
        List<PetType> petTypeTree = new ArrayList<>();
        //遍历所有宠物类型
        for (PetType type : petTypes) {
            if (type.getParentId() == null) {
                //添加到宠物类型树
                petTypeTree.add(type);
            } else {
                Long parent_id = type.getParentId();
                //获取父宠物类型对象
                PetType parentPetType = map.get(parent_id);
                if (parentPetType != null) {
                    //将自己状态父宠物类型的children集合中
                    parentPetType.getChildren().add(type);
                }
            }
        }
        return petTypeTree;
    }
}
